<?php

namespace App\Admin\Controllers;

use App\Business\BLL\Wechat\WechatPayment;
use App\Http\Controllers\Controller;
use App\Models\Arenacontest;
use App\Models\ArenacontestUser;
use App\Models\CityList;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use App\Models\WechatUser;
use App\Models\ArenacontestUserUser;

class ArenacontestUserController extends Controller
{
    use HasResourceActions;

    private $name = '擂台赛报名者';

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header($this->name)
            ->description(trans('admin.list'))
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header($this->name)
            ->description(trans('admin.detail'))
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header($this->name)
            ->description(trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header($this->name)
            ->description(trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ArenacontestUser);
//        $grid->model()->where('status', '>', 0)->orderBy('id', 'desc');

        $grid->wxcode('微信号');
        $grid->contact('联系方式');
        $grid->status('报名状态')->display(function ($status) {
            return ArenacontestUser::status($status);
        });
        $grid->pay_status('缴费状态')->display(function ($status) {
            return ArenacontestUser::payStatus($status);
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $ArenacontestUser = ArenacontestUser::findOrFail($id);
        $show = new Show($ArenacontestUser);
        $Arenacontest = Arenacontest::findOrFail($ArenacontestUser['arenacontest_id']);
        $arenacontestShow = new Show($Arenacontest);

        $arenacontestShow->id('ID');
        $arenacontestShow->city('城市')->unescape()->as(function ($city) {
            return Arenacontest::cityInfoByKey($city)['name'];
        });
        $arenacontestShow->organizer_name('擂主名称');
        $arenacontestShow->title('标题');
        $arenacontestShow->game_datetime('比赛开始时间');
        $arenacontestShow->end_game_datetime('比赛结束时间');
        $arenacontestShow->address('比赛地点');
        $arenacontestShow->signup_datetime('报名截止');
        $arenacontestShow->signup_price('报名费');
        $arenacontestShow->remark('简介');
        $arenacontestShow->integral('报名积分限制');
        $arenacontestShow->desc('描述')->unescape()->as(function ($desc) {
            return $desc;
        });
        // 去掉`继续编辑`checkbox
        $arenacontestShow->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableList();
                $tools->disableDelete();
            });;
        $arenacontestShow->signup('报名者', function ($signup) {
            $signup->setResource('/admin/ArenacontestUser');
            $signup->user()->name('名称');
            $signup->wxcode('微信号');
            $signup->contact('联系方式');
            $signup->status('报名状态')->display(function ($status) {
                return ArenacontestUser::getstatus($status);
            });
            $signup->pay_status('缴费状态')->display(function ($status) {
                return ArenacontestUser::getpayStatus($status);
            });
            $signup->disableExport();
            $signup->disableCreateButton();
            $signup->disableRowSelector();
            $signup->actions(function ($actions) {
                $actions->disableView();
            });
        });

        return $arenacontestShow;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ArenacontestUser);
        // 去掉`重置`按钮
        $form->disableReset();
        // 去掉`查看`checkbox
        $form->disableViewCheck();
        // 去掉`继续编辑`checkbox
        $form->disableEditingCheck();
        // 去掉`继续创建`checkbox
        $form->disableCreatingCheck();
        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });
        $form->setTitle('报名者审核');
        $form->text('wxcode', '微信号')->readonly();
        $form->text('contact', '联系方式')->readonly();

        // 自定义渲染字段
        $form->html(function () use ($form) {
            // 获取 model 属性值
            $value = $form->model()->ball_video ?? '';
            $disk = \Storage::disk('qiniu');
            $bg = $disk->url($value);
            // 自定义 HTML 渲染
            echo '<div class="form-group">
               <label for="contact" class="col-sm-2  control-label">视频介绍</label>
            <video controls="" autoplay="" name="media" style="width: 400px;height: 300px;"><source src="' . $bg . '" type="video/mp4"></video>
            </div>';
        });
        $form->select('pay_status', '缴费状态')->options([10 => '待缴费', 20 => '已缴费', 30 => '已退费'])->readonly();
        $form->select('status', '报名状态')->options([10 => '等待审核', 20 => '审核通过']);

        $form->saved(function (Form $form) {
            return redirect(admin_url("/arenacontest"));
        });
        return $form;
    }

    public function confirm($id)
    {
        $ArenacontestUser = ArenacontestUser::find($id);
        if ($ArenacontestUser->status != 10) {
            admin_toastr('当前赛事已经确认过了', 'error');
            return back();
        }
        $ArenacontestUser->status = 20;
        if ($ArenacontestUser->save()) {
            admin_toastr('确认成功', 'success');
        } else {
            admin_toastr('确认失败', 'error');
        }

        $url = route('ArenacontestUser.index');
        return redirect($url);
    }

    public function close($id)
    {
        $ArenacontestUser = ArenacontestUser::find($id);
        if ($ArenacontestUser->status != 20) {
            admin_toastr('当前赛事不是比赛中，不能结案', 'error');
            return back();
        }
        $ArenacontestUser->status = 30;
        if ($ArenacontestUser->save()) {
            admin_toastr('确认成功', 'success');
        } else {
            admin_toastr('确认失败', 'error');
        }

        $url = route('ArenacontestUser.index');
        return redirect($url);
    }

    public function refundOrder($id)
    {
        $order = ArenacontestUser::findOrFail($id);

        if ($order->pay_status == 10) {
            $data = [
                'status' => false,
                'message' => '订单未付款无法退款',
            ];
        }

        if ($order->pay_status == 30) {
            $data = [
                'status' => false,
                'message' => '订单已退款，请勿重复操作',
            ];
        }
        if ($order->price <=0) {
            $data = [
                'status' => false,
                'message' => '金额错误',
            ];
        }
        if (empty($order->transid)) {
            $data = [
                'status' => false,
                'message' => '微信订单号错误',
            ];
        }

        $app = WechatPayment::make();
        // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
        $refundno=getrefundSN();
        $result = $app->refund->byTransactionId($order->transid, $refundno, $order->price*100, $order->price*100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退还擂台赛押金',
        ]);
        if ($result['return_code'] === 'SUCCESS'){
            // 执行退款逻辑
            $refundId = $result['refund_id'];
            $order->pay_status=30;
            $order->refundstate=4;
            $order->refundtime=date("Y-m-d H:i:s");;
            $order->refundno=$refundno;
            $order->refund_id=$refundId;
            $order->save();
            $data = [
                'status' => true,
                'message' => '退款成功',
            ];
        }else{
            $data = [
                'status' => false,
                'message' => $result['err_code_des'],
            ];
        }

        return response()->json($data);
    }
}
